package cn.newgrand.netcall.integration.setting;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

import javax.swing.Icon;
import javax.swing.JComponent;

import org.jivesoftware.Spark;
import org.jivesoftware.spark.preference.Preference;
import org.jivesoftware.spark.util.SwingWorker;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.sparkimpl.preference.sounds.SoundPreferences;

import cn.newgrand.common.StringUtil;
import cn.newgrand.netcall.integration.AppSysRes;

import com.thoughtworks.xstream.XStream;
/**
 * @author SidneyRen E-mail:SidneyRen@hotmail.com
 * @version create time：2010-12-30 下午07:02:06
 * 类说明
 */
public class SettingPreference implements Preference{
	
	/*
	 * debug模式下可以读取integration-settings.xml信息
	 * 但是应用程序直接启动不能解析integration-settings.xml文件
	 * 异常com.thoughtworks.xstream.alias.CannotResolveClassException: 
	 * cn.newgrand.netcall.integration.setting.SettingPreferences
	 * --所以改将信息保存到spark.properties
	 */

	private XStream xstream;
	private SettingPanel panel;
    private SettingPreferences preferences;
	public static String NAMESPACE = "IntegrationSetting";
	
	@Override
	public String getTitle() {
		return "设置登入应用系统参数";
	}

	@Override
	public Icon getIcon() {
		return AppSysRes.getImageIcon(AppSysRes.INTEGRATION_IMAGE);
	}

	@Override
	public String getTooltip() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getListName() {
		return "集成设置";
	}

	@Override
	public String getNamespace() {
		return NAMESPACE;
	}

	@Override
	public JComponent getGUI() {
		panel = new SettingPanel();

        return panel;
	}
	
	public void loadFromFile(){
		if (preferences != null) {
			return;
		}

		if (!getSettingsFile().exists()) {
			preferences = new SettingPreferences();
		} else {

			// Do Initial Load from FileSystem.
			File settingsFile = getSettingsFile();
			try {
				FileReader reader = new FileReader(settingsFile);
				preferences = (SettingPreferences) getXStream().fromXML(reader);
				// 检查服务器设置的地址和客户端保存的是否相同
				// if (!preferences
				// .getSelectedLoginURL()
				// .equals(AppSysRes
				// .getString(AppSysRes.APP_SERVER_LOGIN_URL_INTERNET))
				// &&!preferences
				// .getSelectedLoginURL()
				// .equals(AppSysRes
				// .getString(AppSysRes.APP_SERVER_LOGIN_URL_INTRANET))) {
				// preferences = new SettingPreferences();
				// }
				if (StringUtil.isEmpty(preferences.getLoginURLInternet())) {
					preferences
							.setLoginURLInternet(AppSysRes
									.getPropertyOnServer(AppSysRes.APP_SERVER_LOGIN_URL_INTERNET));
				}
				if (StringUtil.isEmpty(preferences.getLoginURLIntranet())) {
					preferences
							.setLoginURLIntranet(AppSysRes
									.getPropertyOnServer(AppSysRes.APP_SERVER_LOGIN_URL_INTRANET));
				}
			} catch (Exception e) {
				Log.error("Error loading Sound Preferences.", e);
				preferences = new SettingPreferences();
			}
		}
	}
	
	public SettingPreferences loadFromProperties(){
		final Properties props = new Properties();
		if(preferences != null){
			return preferences;
		}
		if(!getSettingsProperties().exists()){
			preferences = new SettingPreferences();
		}else{
			try {
				props.load(new FileInputStream(getSettingsProperties()));
				preferences = new SettingPreferences(props);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return preferences;
	}
	
	private File getSettingsProperties(){
		File file = new File(Spark.getSparkUserHome());
        if (!file.exists()) {
            file.mkdirs();
        }
        return new File(file, "integration-settings.properties");
	}
	
	private File getSettingsFile() {
        File file = new File(Spark.getSparkUserHome());
        if (!file.exists()) {
            file.mkdirs();
        }
        return new File(file, "integration-settings.xml");
    }

	@Override
	public void load() {
		
		if (panel == null) {
			 panel = new SettingPanel();
	    }
		preferences = loadFromProperties();
        SwingWorker worker = new SwingWorker() {
            public Object construct() {
                return preferences;
            }

            public void finished() {
                // Set default settings
            	panel.setLoginURLIntranet(preferences.getLoginURLIntranet());
            	panel.setSelectedIntranet(preferences.isSelectedIntranet());

            	panel.setLoginURLInternet(preferences.getLoginURLInternet());
            	panel.setSelectedInternet(preferences.isSelectedInternet());
            	
            	panel.setAwayTime(preferences.getAwayTime());
            	panel.setOfflineTime(preferences.getOfflineTime());
            }
        };
        worker.start();
		
	}

	@Override
	public void commit() {
		preferences.setLoginURLInternet(panel.getLoginURLInternet());
		preferences.setLoginURLIntranet(panel.getLoginURLIntranet());
		preferences.setSelectedInternet(panel.isSelectedInternet());
		preferences.setSelectedIntranet(panel.isSelectedIntranet());
		preferences.setAwayTime(panel.getAwayTime());
		preferences.setOfflineTime(panel.getOfflineTime());
		saveProperties();
		
	}

	@Override
	public boolean isDataValid() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public String getErrorMessage() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object getData() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void shutdown() {
		// TODO Auto-generated method stub
		
	}
	
	public SettingPreferences getPreferences() {
        if (preferences == null) {
            load();
        }
        return preferences;
    }
	
	private void saveFile() {
        try {
            FileWriter writer = new FileWriter(getSettingsFile());
            getXStream().toXML(preferences, writer);
        }
        catch (Exception e) {
            Log.error("Error saving sound settings.", e);
        }
    }
	
	private void saveProperties(){
		try {
			Properties props = preferences.getProps();
			props.store(new FileOutputStream(getSettingsProperties()), "integration-settings");
		} catch (Exception e) {
			Log.error("Error saving integration-settings.properties settings.", e);
		}
	}

	private XStream getXStream() {
		if (xstream == null) {
			xstream = new XStream();
			xstream.alias("integrationSetting", SettingPreferences.class);
		}
		return xstream;
	}

}
